package cn.itcast.dao;

import cn.itcast.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;

import java.util.List;

public interface RoleDao {

    /**
     * 根据userId查询角色以及关联的permissions表
     * @param userId
     * @return
     * @throws Exception
     */
    @Select("select * from role where id in " +
            "(select roleId from users_role where userId = #{userId})")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.itcast.dao.PermissionDao.findByRoleId"))
    })
    List<Role> findRoleByUserId(String userId) throws Exception;


    /**
     * 查询所有角色
     * @return
     */
    @Select("select * from role")
    List<Role> findAll() throws Exception;

    /**
     * 根据idc查询角色
     * @param id
     * @return
     * @throws Exception
     */
    @Select("select * from role where id = #{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.itcast.dao.PermissionDao.findByRoleId")),
    })
    Role findById(String id)throws Exception;

    /**
     *
     * 添加角色
     * @param role
     */
    @Insert("insert into role (roleName,roleDesc) values (#{roleName},#{roleDesc})")
    void save(Role role);


    /**
     * 根据用户id查询该用户可以添加的角色
     * @param userId
     * @return
     */
    /*@Select("select * from role where id not in " +
            "(select roleId from users_role where userId=#{userId})")*/
    @Select("select * from role where id not in " +
            "(select roleId from users_role where userId = #{userId})")
    List<Role> findOtherRoles(String userId);

    /**
     * 给角色添加权限
     * @param roleId
     * @param permissionId
     */
    @Insert("insert into role_permission (permissionId,roleId) values(#{permissionId},#{roleId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);
}
